<template>
  <div id="login-form">
    <a-form :form="form" style="margin-top: 48px">
      <a-form-item label="用户名">
        <a-input
          v-decorator="[
            'username',
            { rules: [{ required: true, message: 'Please input your name' }] },
          ]"
        ></a-input>
      </a-form-item>
      <a-form-item label="密码">
        <a-input
          v-decorator="[
            'password',
            { rules: [{ required: true, message: 'Please input your name' }] },
          ]"
        ></a-input>
      </a-form-item>
      <a-form-item>
        <a-spin :spinning="spinning">
          <a-button type="primary" @click="handleLogin" class="login-form-button">
          登录
          </a-button>
        </a-spin>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
export default {
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'login' });
  },
  mounted() {
    this.form.setFieldsValue({
      username: 'admin',
      password: 'admin',
    });
  },
  data() {
    return {
      spinning: false,
    };
  },
  methods: {
    async handleLogin() {
      this.form.validateFields(async (err, value) => {
        if (!err) {
          try {
            const { username, password } = value;
            this.spinning = true;
            await this.$store.dispatch('user/login', {
              username,
              password,
            });
            await this.$store.dispatch('user/getInfo');
            this.spinning = false;
            this.$router.push(
              { path: '/' },
              () => {},
              () => {},
            );
          } catch ({ error }) {
            this.spinning = false;
            if (error) {
              this.$message.error(error.message);
            }
          }
        }
      });
    },
  },
};
</script>

<style scoped>
#login-form .login-form-button {
  width: 100%;
}
</style>
